<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';

import { ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { orderPayExport, orderPayList } from '#/api/business/order-pay';

import { columns, exportSchema, querySchema } from './data';

const formOptions: VbenFormProps = {
  commonConfig: {
    componentProps: {
      allowClear: true,
      class: 'w-full',
    },
  },
  schema: querySchema(),
  showCollapseButton: false,
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
  fieldMappingTime: [
    [
      'createTime',
      ['startDate', 'endDate'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

const gridOptions: VxeGridProps = {
  columns,
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const { dateRange, ...rest } = formValues;
        const params: any = {
          pageNo: page.currentPage,
          pageSize: page.pageSize,
          ...rest,
        };

        // 处理时间范围
        if (dateRange && dateRange.length === 2) {
          params.startDate = dateRange[0];
          params.endDate = dateRange[1];
        }

        return await orderPayList(params);
      },
    },
  },
  rowConfig: {
    keyField: 'orderId',
  },
  id: 'order-pay-index',
};

const [BasicTable, tableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [ExportModal, exportModalApi] = useVbenModal({
  onConfirm: handleExport,
});

const exportFormData = ref<any>({});
const isExporting = ref(false);

/**
 * 打开导出弹窗
 */
const openExportModal = async () => {
  const pageNo = tableApi.grid.getCurrentPage();
  const pageSize = tableApi.grid.getPageSize();

  const params: any = {
    pageNo,
    pageSize,
    ...tableApi.formApi.form.values,
  };
  const blob = await orderPayExport(params);

  // 创建下载链接
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = `支付对账_${Date.now()}.xlsx`;
  document.body.append(link);
  link.click();
  link.remove();
  window.URL.revokeObjectURL(url);

  message.success('导出成功');
};

/**
 * 导出数据
 */
async function handleExport() {
  const { dateRange, ...rest } = exportFormData.value;
  const params: any = {
    pageNo: 1,
    pageSize: 36,
    ...rest,
  };

  // 处理时间范围
  if (dateRange && dateRange.length === 2) {
    params.startDate = dateRange[0];
    params.endDate = dateRange[1];
  }

  try {
    isExporting.value = true;
    const blob = await orderPayExport(params);

    // 创建下载链接
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `支付对账_${Date.now()}.xlsx`;
    document.body.append(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(url);

    message.success('导出成功');
    exportModalApi.close();
  } catch {
    message.error('导出失败');
  } finally {
    isExporting.value = false;
  }
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="支付对账">
      <template #toolbar-tools>
        <a-button
          type="primary"
          @click="openExportModal"
          v-access:code="['sys:order:pay:export']"
        >
          导出
        </a-button>
      </template>
    </BasicTable>

    <ExportModal
      title="导出支付对账"
      :loading="isExporting"
      :confirm-loading="isExporting"
    >
      <vben-form
        v-model:values="exportFormData"
        :schema="exportSchema()"
        class="mt-4"
        wrapper-class="grid-cols-1"
      />
    </ExportModal>
  </Page>
</template>
